package com.cedarhd.finance.msg.domain.service;

import com.cedarhd.finance.msg.dto.MailDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @author Evan
 * @date 2018/3/6
 */
@Service
public class MailService {

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private JavaMailSender javaMailSender;

    private Logger logger = LoggerFactory.getLogger(MailService.class);
    /**
     * 发送邮件
     * @param dto
     * @return
     */
    public boolean send(MailDTO dto){
        boolean result = false;

        String[] toAddressArray = dto.getToAddress().split(",");

        for(String address:toAddressArray){
            SimpleMailMessage message = new SimpleMailMessage();
            logger.info("send mail toaddress={}", address);
            // 在setFrom处必须填写自己的邮箱地址，否则会报
            // Failed messages: com.sun.mail.smtp.SMTPSendFailedException:
            // 501 mail from address must be same as authorization user错误
            message.setFrom(username);
            message.setTo(address);
            message.setSubject(dto.getSubject());
            message.setText(dto.getContent());
            try {
                javaMailSender.send(message);
                result = true;
            }catch (Exception e){
                logger.error("send mail failed !",e);
            }
        }
        return result;

    }


}
